package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Tags;
import com.hxkj.domain.po.WebsiteAddr;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_NEWARTICLE;

/**
 * 自定义标签
 * 最新文章 日排行 周排行
 *
 * @author chenfangzhou 2018/09/14
 */
@Component
@Slf4j
public class NewArticleDirective extends AbstractDirective {
    @Autowired
    private ArticleServiceClient articleServiceClient;
    @Autowired
    private RedisTemplate redisTemplate;

    //站点id
    private static final String SITE_ID = "siteId";
    //获取文章的条数
    private static final String COUNT = "count";

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        try {
            Long siteId = getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : getLong(SITE_ID, params);
            String userToken = super.getUserToken(env);
            String note = super.getNote(env);
            Integer count = getInt(COUNT, params) == null ? 10 : getInt(COUNT, params);

            // 查找redis缓存
            List<Article> dailyArticleList = (List<Article>) redisTemplate.boundValueOps("directive_" + siteId + CMS_NEWARTICLE + "_dailyArticleList").get();
            List<Article> weeklyArticleList = (List<Article>) redisTemplate.boundValueOps("directive_" + siteId + CMS_NEWARTICLE + "_weeklyArticleList").get();
            if (null == dailyArticleList || dailyArticleList.size() == 0 || null == weeklyArticleList || weeklyArticleList.size() == 0) {
                Article article_ = new Article();
                article_.setSiteId(siteId);
                article_.setCount(count);

                // 日最新文章
                dailyArticleList = articleServiceClient.getDailyArticleList(article_);

                // 周最新文章
                weeklyArticleList = articleServiceClient.getWeeklyArticleList(article_);

                // 添加redis缓存
                redisTemplate.boundValueOps("directive_" + siteId + CMS_NEWARTICLE + "_dailyArticleList").set(dailyArticleList);
                redisTemplate.boundValueOps("directive_" + siteId + CMS_NEWARTICLE + "_weeklyArticleList").set(weeklyArticleList);
            }

            WebsiteAddr webSiteAddr = getWebSiteAddr(siteId);
            if (StringUtils.isNotBlank(note)) {
                if (dailyArticleList != null && dailyArticleList.size() > 0) {

                    for (Article arc : dailyArticleList) {
                        arc.setManuscriptPath(webSiteAddr.getIpAdd() + arc.getManuscriptPath());
                    }
                }
                if (weeklyArticleList != null && weeklyArticleList.size() > 0) {

                    for (Article arc : weeklyArticleList) {
                        arc.setManuscriptPath(webSiteAddr.getIpAdd() + arc.getManuscriptPath());
                    }
                }
            }else {
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                // 静态文件文章链接加前缀
                for (Article item : dailyArticleList) {
                    String urlContext = siteCtxMap.get(siteId);
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
                for (Article item : weeklyArticleList) {
                    String urlContext = siteCtxMap.get(siteId);
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }
            env.setVariable("dailyArticleList", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(dailyArticleList));
            env.setVariable("weeklyArticleList", DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(weeklyArticleList));


            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_NEWARTICLE, "");
                    maps.put(SITE_ID, String.valueOf(getLong(SITE_ID, params)));
                    maps.put(COUNT, String.valueOf(getInt(COUNT, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                log.debug("文章详情所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
